package com.ansion.commonchat.startup;

import android.net.Uri;

import com.ansion.commonchat.startup.fresco.fetcher.IFrescoFetcher;
import com.ansion.log.VLog;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.producers.BaseNetworkFetcher;
import com.facebook.imagepipeline.producers.Consumer;
import com.facebook.imagepipeline.producers.FetchState;
import com.facebook.imagepipeline.producers.ProducerContext;
import com.facebook.imagepipeline.request.ImageRequest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by yangke on 16/6/18.
 */
public class CustomFrescoFetcher extends BaseNetworkFetcher<FetchState> implements IFrescoFetcher<FetchState> {

    private static final int NUM_NETWORK_THREADS = 5;
    private static final String TAG = "Fresco";

    private final ExecutorService mExecutorService;

    public CustomFrescoFetcher() {
        mExecutorService = Executors.newFixedThreadPool(NUM_NETWORK_THREADS);
    }

    @Override
    public FetchState createFetchState(Consumer<EncodedImage> consumer, ProducerContext producerContext) {
        return new FetchState(consumer, producerContext);
    }

    @Override
    public void fetch(final FetchState fetchState, final Callback callback) {
        final Future<?> future = mExecutorService.submit(
                new Runnable() {
                    @Override
                    public void run() {
                        HttpURLConnection connection = null;
                        Uri uri = fetchState.getUri();
                        String scheme = uri.getScheme();
                        String uriString = fetchState.getUri().toString();
                        if (VLog.OPEN_LOG) {
                            VLog.tick(uriString);
                        }
                        while (true) {
                            String nextUriString;
                            String nextScheme;
                            InputStream is;
                            try {
//                                ServiceMappingManager.MappedURLConnection mappedConn = ServiceMappingManager.getSingleton().openURLConnection(uriString, true);
//                                connection = mappedConn.connection;
//                                nextUriString = connection.getHeaderField("Location");
//                                nextScheme = (nextUriString == null) ? null : Uri.parse(nextUriString).getScheme();
//                                if (nextUriString == null || nextScheme.equals(scheme)) {
//                                    if (VLog.OPEN_LOG) {
//                                        String redirectUri = connection.getURL().toString();
//                                        if (!uriString.equals(redirectUri)) {
//                                            VLog.d(TAG, "redirect uri from (%s) to (%s) with host(%s)", uriString, redirectUri, connection.getRequestProperty("Host"));
//                                        }
//                                    }
//                                    is = connection.getInputStream();
//                                    //这里的aesKey不用再走urlDecode了，因为getQueryParameter中自动做了urlDecode，多做一次会出错
//                                    String aesKey = uri.getQueryParameter("aesKey");
//                                    String frameSize = uri.getQueryParameter("frameSize");
//                                    if (!TextUtils.isEmpty(aesKey) && !TextUtils.isEmpty(frameSize)) {
//                                        int contentLength = connection.getContentLength();
//                                        VLog.FileLog.i("TAG_E2E", "Fresco decryptImage:%s,contentLength:%d", uriString, contentLength);
//                                        is = decryptImage(is, aesKey, contentLength, ValueSafeTransfer.intValue(frameSize));
//                                    }
//                                    callback.onResponse(is, -1);
//                                    break;
//                                }
//                                uriString = nextUriString;
//                                scheme = nextScheme;
                            } catch (Throwable e) {
                                callback.onFailure(e);
                                break;
                            } finally {
                                if (connection != null) {
                                    connection.disconnect();
                                }
                            }
                        }

                        if (VLog.OPEN_LOG) {
                            VLog.d(TAG, "Request Image with uri(%s) waste (%s)", uriString, VLog.stop(uriString).getWaste());
                        }
                    }
                });
    }

    @Override
    public int order() {
        return ORDER_SOFT_DNS;
    }

    @Override
    public boolean interrupt(ImageRequest request) {
        return true;
    }


    InputStream decryptImage(InputStream is, String aesKey, int contentLength, int frameSize) {
        ByteArrayOutputStream bos = null;
        FileInputStream fis = null;
//        try {
//            bos = new ByteArrayOutputStream();
//            File file = new File(new BOTStorage().getTempPath(), BOTStorage.IMAGES);
//            file.mkdirs();
//            File tmpFile = new File(file, UUID.randomUUID().toString() + ".jpg");
//            FileUtils.copyInputStreamToFile(is, tmpFile);
//            fis = new FileInputStream(tmpFile);
//            FileDecryptUtil.decryptBytesV2(aesKey, contentLength, fis, bos, frameSize);
//            FileUtil.removeFile(tmpFile);
//        } catch (Exception e) {
//            VLog.e(e, LogTag.TAG_E2E, "decryptBytes fail");
//        } finally {
//            FileUtil.safeClose(fis);
//            FileUtil.safeClose(bos);
//        }
        return new ByteArrayInputStream(bos.toByteArray());

    }

}
